// SMT业务流程相关命令

// 登录/输入订单号
Cypress.Commands.add('inputOrderNo', (orderNo) => {
  cy.get('input[placeholder*="订单"]').clear().type(orderNo)
  cy.get('.btn-start').click()
  cy.waitForPageLoad()
})

// 输入作业员ID
Cypress.Commands.add('inputOperatorId', (operatorId) => {
  cy.get('input[placeholder*="作业员"]').clear().type(operatorId)
  cy.get('.btn-start').click()
  cy.waitForPageLoad()
})

// 扫描物料批次ID
Cypress.Commands.add('scanPartBatch', (partBatchId) => {
  cy.get('.hidden-input').focus()
  cy.get('.hidden-input').type(partBatchId + '{enter}')
  cy.wait(500) // 等待扫描处理
})

// 验证扫描结果
Cypress.Commands.add('verifyOrderData', (expectedData) => {
  if (expectedData.orderNo) {
    cy.contains(expectedData.orderNo).should('be.visible')
  }
  if (expectedData.mounterId) {
    cy.contains(expectedData.mounterId).should('be.visible')
  }
  if (expectedData.operatorName) {
    cy.contains(expectedData.operatorName).should('be.visible')
  }
})

// 验证扫描状态
Cypress.Commands.add('verifyStatus', (expectedStatus) => {
  cy.get('.status-value').should('contain.text', expectedStatus)
})

// 完成工作流程
Cypress.Commands.add('completeWorkflow', () => {
  cy.get('.btn-complete').click()
  cy.waitForPageLoad()
})

// 返回上一页
Cypress.Commands.add('goBack', () => {
  cy.get('.btn-back').click()
  cy.waitForPageLoad()
})

// 模拟管理员确认
Cypress.Commands.add('confirmAdmin', () => {
  cy.get('.auth-button-confirm').click()
  cy.waitForPageLoad()
})

// Custom command for API requests with proper error handling
Cypress.Commands.add('apiRequest', (method, endpoint, body = null) => {
  const baseUrl = Cypress.env('BACKEND_URL') || 'http://localhost:8001'
  
  return cy.request({
    method: method,
    url: `${baseUrl}${endpoint}`,
    body: body,
    failOnStatusCode: false, // Don't fail on HTTP error codes
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    timeout: 30000
  }).then((response) => {
    // Log request details for debugging
    cy.log(`🌐 ${method} ${endpoint}`)
    if (body) {
      cy.log(`📤 Request: ${JSON.stringify(body)}`)
    }
    cy.log(`📥 Response: ${response.status} - ${JSON.stringify(response.body)}`)
    
    return response
  })
})

// Custom command for clearing all caches in UniApp environment
Cypress.Commands.add('clearAllCaches', () => {
  cy.window().then((win) => {
    if (win.uni && win.uni.clearStorageSync) {
      try {
        // 获取清理前的状态
        const beforeClear = win.uni.getStorageInfoSync()
        cy.log(`🧹 清理前缓存键数量: ${beforeClear.keys.length}`)
        
        // 执行全量清理
        win.uni.clearStorageSync()
        
        // 验证清理结果
        const afterClear = win.uni.getStorageInfoSync()
        cy.log(`✅ 清理后缓存键数量: ${afterClear.keys.length}`)
        
        if (afterClear.keys.length > 0) {
          cy.log(`⚠️ 仍有${afterClear.keys.length}个缓存键未清理: ${afterClear.keys.join(', ')}`)
        }
      } catch (error) {
        cy.log(`❌ 缓存清理失败: ${error.message}`)
      }
    } else {
      cy.log('⚠️ uni.clearStorageSync不可用，跳过缓存清理')
    }
  })
})

// Custom command for setting up test cache data
Cypress.Commands.add('setupTestCache', (cacheKey, testData) => {
  cy.window().then((win) => {
    if (win.uni && win.uni.setStorageSync) {
      try {
        win.uni.setStorageSync(cacheKey, testData)
        cy.log(`📦 测试缓存已设置: ${cacheKey}`)
        
        // 验证设置成功
        const retrievedData = win.uni.getStorageSync(cacheKey)
        if (JSON.stringify(retrievedData) === JSON.stringify(testData)) {
          cy.log('✅ 缓存设置验证成功')
        } else {
          cy.log('❌ 缓存设置验证失败')
        }
      } catch (error) {
        cy.log(`❌ 设置测试缓存失败: ${error.message}`)
      }
    } else {
      cy.log('⚠️ uni.setStorageSync不可用')
    }
  })
})

// Custom command for verifying cache state
Cypress.Commands.add('verifyCacheState', (expectedKeys = [], shouldBeEmpty = false) => {
  cy.window().then((win) => {
    if (win.uni && win.uni.getStorageInfoSync) {
      try {
        const storageInfo = win.uni.getStorageInfoSync()
        
        cy.log(`🔍 当前缓存状态:`)
        cy.log(`   - 键数量: ${storageInfo.keys.length}`)
        cy.log(`   - 当前大小: ${storageInfo.currentSize}KB`)
        cy.log(`   - 所有键: ${storageInfo.keys.join(', ')}`)
        
        if (shouldBeEmpty) {
          expect(storageInfo.keys.length).to.equal(0)
          cy.log('✅ 缓存已清空验证成功')
        }
        
        if (expectedKeys.length > 0) {
          expectedKeys.forEach(key => {
            expect(storageInfo.keys).to.include(key)
          })
          cy.log(`✅ 期望的缓存键存在: ${expectedKeys.join(', ')}`)
        }
        
        return storageInfo
      } catch (error) {
        cy.log(`❌ 缓存状态验证失败: ${error.message}`)
        return null
      }
    } else {
      cy.log('⚠️ uni.getStorageInfoSync不可用')
      return null
    }
  })
})

// Custom command for cache performance testing
Cypress.Commands.add('testCachePerformance', (dataSize = 1000) => {
  cy.window().then((win) => {
    if (win.uni && win.uni.setStorageSync && win.uni.getStorageSync) {
      const startTime = Date.now()
      
      // 创建性能测试数据
      const performanceTestData = new Array(dataSize).fill(0).map((_, i) => ({
        id: i,
        data: `performance_test_${i}`,
        timestamp: Date.now(),
        metadata: {
          index: i,
          created: new Date().toISOString()
        }
      }))
      
      // 测试写入性能
      const writeStartTime = Date.now()
      win.uni.setStorageSync('performanceTest', performanceTestData)
      const writeEndTime = Date.now()
      const writeTime = writeEndTime - writeStartTime
      
      cy.log(`⏱️ 缓存写入性能 (${dataSize}项): ${writeTime}ms`)
      
      // 测试读取性能
      const readStartTime = Date.now()
      const retrievedData = win.uni.getStorageSync('performanceTest')
      const readEndTime = Date.now()
      const readTime = readEndTime - readStartTime
      
      cy.log(`⏱️ 缓存读取性能 (${dataSize}项): ${readTime}ms`)
      
      // 验证数据完整性
      expect(retrievedData).to.have.length(dataSize)
      expect(retrievedData[0].id).to.equal(0)
      expect(retrievedData[dataSize-1].id).to.equal(dataSize-1)
      
      cy.log('✅ 缓存性能测试完成')
      
      // 清理性能测试数据
      win.uni.removeStorageSync('performanceTest')
      
      return {
        writeTime,
        readTime,
        dataSize
      }
    } else {
      cy.log('⚠️ 缓存API不可用，跳过性能测试')
      return null
    }
  })
})